<?php

require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Lz.php';


/**
 *  Class for execution time tracking.
 *
 *  @author GoniX aka Giedrius Dubinskas
 */
class LzStopwatch
{
    const       WAIT    = true;

    protected   $start  = NULL;
    protected   $length = NULL;


    public
    function __construct($wait = false)
    {
        if (!$wait)
            $this->begin();
    }


    /**
     *  Starts stopwatch.
     */
    public function
    begin()
    {
        $this->length   = NULL;
        $this->start    = microtime(true);
    }


    /**
     *  Stops stopwatch.
     *
     *  Saves time elapsed time that may be retrieved later calling length()
     *  method.
     *
     *  @return [float] Elapsed time.
     */
    public
    function end()
    {
        if (is_null($this->start))
            throw new LzBadUsage();

        $this->length   = microtime(true) - $this->start;
        $this->start    = NULL;
        return $this->length;
    }


    /**
     *  Returns elapsed time.
     *
     *  If method end() was called elapsed time till that call
     *  else elapsed time since call to begin() method is returned.
     *
     *  @return [float]
     */
    public
    function length()
    {
        if (!is_null($this->length))
            return $this->length;
        else if (!is_null($this->start))
            return microtime(true) - $this->start;
        else
            throw new LzBadUsage();
    }
}

